<script setup lang="tsx">
import { Delete, Edit } from '@element-plus/icons-vue'
import type { Action } from 'element-plus'
import { ElTag } from 'element-plus'
import {
  defaultFormData,
  defaultPagingParams,
} from '../index'
import FormModal from './FormModal.vue'
import SearchForm from './SearchForm.vue'
import type { TableColumn, TeamsInfo } from '@/types'
import {
  deleteById,
  queryList,
  saveOrUpdate,
} from '@/api/modules/teams'
// ------------------use------------------
// #region
const { globalProperties } = useCurrentInstance()
const { withLoading, loading } = useDefineLoading()
const [tableData, setTableData] = useState<TeamsInfo[]>([])
const [formData, setFormData] = useState<any>({
  ...defaultFormData,
})
const [total, setTotal] = useState<number>(0)
const [formModalTitle, setFormModalTitle]
  = useState<string>('')
const { $message } = useCurrentInstance()
// #endregion
// ------------------静态变量------------------
// #region
const columns: TableColumn<TeamsInfo>[] = [
  {
    key: uuid(),
    type: 'index',
    width: '80',
    label: '序号',
  },
  {
    key: uuid(),
    label: '时间',
    render({ row }) {
      return `${row.startTime} - ${row.endTime}`
    },
  },
  {
    key: uuid(),
    label: '班组',
    render({ row }) {
      return h(ElTag, row.teamsName)
      // return h(
      //   'div',
      //   {
      //     class: 'text-overflow-hide'
      //   },
      //   h(ElSpace, null, {
      //     default: () =>
      //       ['A班组', 'B班组', 'C班组'].map(item =>
      //         h(ElTag, null, {
      //           default: () => item
      //         })
      //       )
      //   })
      // );
    },
  },
  {
    key: uuid(),
    label: '测点点位号',
    prop: 'indicatorCode',
  },
]
// #endregion
// ------------------动态变量------------------
// #region

// #endregion
// ------------------ref-----------
// #region
const pagingParams = ref({
  ...defaultPagingParams,
})
const modalRef = ref<InstanceType<typeof FormModal>>()
// #endregion
// ------------------reactive------
// #region

// #endregion
// ------------------computed------
// #region

// #endregion
// ------------------生命周期------------------
// #region
getTableData()
// #endregion
// ------------------内置方法---------------------
// #region

// #endregion
// ------------------方法---------------------
// #region
async function deleteData(id: number) {
  const res: Action = await globalProperties
    .$confirm(
      '该操作将永久删除该数据，确定删除？',
      '警告',
      {
        type: 'warning',
      },
    )
    .catch(e => e)

  if (res !== 'confirm')
    return
  const { code } = await deleteById(id)
  if (code !== 200)
    return
  globalProperties.$message.success('删除成功！')
  getTableData()
}
async function showEditDialog(row: any) {
  setFormModalTitle('编辑')
  setFormData({ ...defaultFormData, ...row })
  await nextTick()
  modalRef.value?.open()
}
async function showAddDialog() {
  setFormModalTitle('新增')
  setFormData({ ...defaultFormData })
  await nextTick()
  modalRef.value?.open()
}
async function getTableData() {
  const { data: res } = await withLoading(queryList)(
    pagingParams.value,
  )
  if (!res) {
    setTotal(0)
    setTableData([])
    return
  }
  const { total, records } = res

  setTotal(total)
  setTableData(records)
}
async function addOrUpdateData(row: Partial<TeamsInfo>) {
  const params = { ...row }
  removeUnnecessaryParams(params)
  const { code } = await saveOrUpdate(params)
  if (code !== 200)
    return
  getTableData()
  $message.success('保存成功！')
  modalRef.value?.close()
}
// #endregion
</script>

<template>
  <div
    class="flex-direction height-fill box-border flex gap-sm"
  >
    <div class="flex-incompressible">
      <slot name="header" />
    </div>
    <div
      class="flex-fillRemaining overflow flex-direction flex align-end"
    >
      <view-table
        :loading="loading"
        :columns="columns"
        :data="tableData"
      >
        <template #actions>
          <SearchForm
            v-model="pagingParams"
            @search="getTableData"
            @reset="getTableData"
            @plus="showAddDialog"
          />
        </template>
        <template #operate="{ row }">
          <TdButton
            title="编辑"
            :icon="Edit"
            type="primary"
            @click="showEditDialog(row)"
          />
          <TdButton
            title="删除"
            :icon="Delete"
            type="danger"
            @click="deleteData(row.id)"
          />
        </template>
      </view-table>

      <!-- 分页 -->
      <ListsPagination
        v-model:page-num="pagingParams.pageNumber"
        v-model:page-size="pagingParams.pageSize"
        :total="total"
        @current-change="getTableData"
        @size-change="getTableData"
      />
    </div>
    <FormModal
      ref="modalRef"
      :title="formModalTitle"
      :data="formData"
      @save-success="addOrUpdateData(formData)"
    />
  </div>
</template>

<style lang="scss" scoped>
//------------------组件样式------------------
//-------------样式穿透-------------
</style>
